<?php
    include_once ("../../includes/config.inc.php");
    check_login();
    $suserSession=get_suser();
    $customer_id=$suserSession['id'];
    $infoModel = new Model_InfoCommon();
    
    //var
    $act = $_POST['act'];
    $type = (int)$_POST['type'];
    $id = (int)$_POST['msgid'];
    $cus_id = $customer_id;
    
    //获取非素材图文列表
    if($act == 'getMsg'){
        $where = "customer_id='{$customer_id}' and info_type='{$type}' and is_mass='2' and state=1";
        $msgArray = $infoModel -> findAll($where);
        if($msgArray){
            foreach ($msgArray as &$val) {
                $val['info_intro'] = cut_str($val['info_intro'], 10);
                $val['info_title'] = cut_str($val['info_title'], 10);
            }
            echo json_encode($msgArray);die;
        }
        echo json_encode('empty');die;
    }
    
    //设置为素材
    if ($act == 'upMsg') {
        $infoModel -> row_update(array('is_mass'=>1),"id='{$id}'");
        echo json_encode('suc');die;
    }

    //设置为非素材
    if ($act == 'del') {
        $infoModel -> row_update(array('is_mass' => 2), "id='{$id}'");
        echo json_encode('suc');die;
    }
    
    //获取token
    $configModel=new Model_CustomerConfig();
    $token=$configModel->getToken($customer_id);
    if (!$token) die(json_encode('无法获取token'));
    //该素材信息
    $msgInfo = $infoModel->findRow("id='{$id}'");
    
    /****************群发还是预览****************/
    $is_preview=1;
    if($is_preview==1){
        $firstStr='"touser":"o7-rgsnLrVXUvSGCa7TwAD1oi_28"';//第一个字串
        $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$token;//接口地址
    }else{
        if($_POST['groupid'] == -1){
            $firstStr='"filter":{"is_to_all":true,"group_id":""}';
        }else{
            $firstStr='"filter":{"is_to_all":false,"group_id":"'.$_POST['groupid'].'"}';
        }
        $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$token;
    }
    
    //推送文本、单图文消息
    if ($act == 'send') {
        if ($type == 1){
            sendText($msgInfo,$firstStr,$mass_api_url);
        }elseif ($type == 2){
            sendSingle($msgInfo,$firstStr,$mass_api_url,$token);
        }
        echo json_encode('suc');die;
    }

    //上传多图文中的素材并推送
    if ($act == 'sendMulti'){
        //更新info_common_detail中图片的media_id
        $detailModel = new Model_InfoCommonDetail;
        $detailArr = $detailModel -> findAll("info_common_id='".$msgInfo[id]."'");
        if($detailArr){
            foreach($detailArr as $k=>$v){
                $detailUpdata=array();
                $detailUpdata['media_id'] = upImage($v['pic'],$token);
                $detailModel -> row_update($detailUpdata, "id='".$v['id']."'");
            }
        }
        
        sendMulti($msgInfo,$firstStr,$mass_api_url,$token);
        echo json_encode('suc');die;
    }

    //发送文本消息
    function sendText($msgInfo,$firstStr,$mass_api_url) {
        $jsonStr = '{
           '.$firstStr.',
           "text":{"content":"'.$msgInfo['info_intro'].'"},
           "msgtype":"text"
        }';
        //file_put_contents('cc.txt',$mass_api_url.'--'.$jsonStr,FILE_APPEND);$returnArray['errcode']=0;
        $returnArray = http_request_curl($mass_api_url,$jsonStr);
        
        if($returnArray['errcode'] == 0){
            setSend($msgInfo['id']);//设置该素材为已发送状态
            return;
        }
        die(json_encode($returnArray['errmsg']));
    }

    //发送单图文
    function sendSingle($msgInfo,$firstStr,$mass_api_url,$token) {
        //获取上传的图片素材的media_id
        $media_id = upImage($msgInfo['info_pic'],$token);
        //获取图文消息素材的media_id
        if(!$msgInfo['info_url']){//无外链的访问微沟通服务器上的一个定制页面
            $msgInfo['info_url']='http://'.$_SERVER['HTTP_HOST'] .'/'.DIR_NAME. "/mobile/info.php?t=single&id=".$msgInfo['id'];
        }
        if(strstr($msgInfo['info_intro'],"='") || strstr($msgInfo['info_intro'],'="')){//引号未转义
            $msgInfo['info_intro']=addslashes($msgInfo['info_intro']);
        }
        
        //获取图文消息素材的media_id
        $jsonStr = '{
           "articles":[
                {
                    "thumb_media_id":"'.$media_id .'",
                    "title":"'.$msgInfo['info_title'].'",
                    "content_source_url":"'.$msgInfo['info_url'].'",
                    "content":"'.$msgInfo['info_intro'].'",
                    "digest":"'.$msgInfo['info_desc'].'",
                    "show_cover_pic":"0"
                }
           ]
        }';
        $upImgUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$token;
        $returnArray = http_request_curl($upImgUrl,$jsonStr);

        //保存 media_id
        /* $updata=array();
        $updata['media_id'] = $returnArray['media_id'];
        $infoModel = new Model_InfoCommon();
        $infoModel->row_update($updata, "id='".$msgInfo[id]."'"); */

        //推送图文消息
        $newsJsonStr = '{
           '.$firstStr.',
           "mpnews":{"media_id":"'.$returnArray['media_id'].'"},
           "msgtype":"mpnews"
        }';
        //file_put_contents('cc.txt',$mass_api_url.'--'.$newsJsonStr,FILE_APPEND);$returnBack['errcode']=0;
        $returnBack = http_request_curl($mass_api_url,$newsJsonStr);

        if($returnBack['errcode'] == 0){
            setSend($msgInfo['id']);
            return;
        }
        die(json_encode($returnBack['errmsg']));
    }

    //发送多图文
    function sendMulti($msgInfo,$firstStr,$mass_api_url,$token){
        $detailModel = new Model_InfoCommonDetail;
        $multiArray = $detailModel -> findAll("info_common_id='".$msgInfo['id']."'", '*', 'order_num asc');

        //获取多图文的media_id
        $siglePageUrl='http://'.$_SERVER['HTTP_HOST'] .'/'.DIR_NAME. "/mobile/info.php?t=multi&id=";
        $jsonStr = '{"articles":[';
        foreach ($multiArray as $val){
            if(!$val['url']) $val['url']=$siglePageUrl.$val['id'];//无外链的访问定制页面
            if(strstr($val['msg_content'],"='") || strstr($val['msg_content'],'="')){//引号未转义
                $val['msg_content']=addslashes($val['msg_content']);
            }
            
            $jsonStr .= '{
                "thumb_media_id":"'.$val['media_id'].'",
                 "title":"'.$val['title'].'",
                 "content_source_url":"'.$val['url'].'",
                 "content":"'.$val['msg_content'].'",
                 "show_cover_pic":"0"
            },';
        }
        $jsonStr = rtrim($jsonStr, ',') . ']}';
        $multiUpApi = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$token;
        $multiMediaMsg = http_request_curl($multiUpApi,$jsonStr);

        //推送多图文
        $jsonStr = '{
           '.$firstStr.',
           "mpnews":{"media_id":"'.$multiMediaMsg['media_id'].'"},
           "msgtype":"mpnews"
        }';
        //file_put_contents('cc.txt',$mass_api_url.'--'.$jsonStr,FILE_APPEND);$returnArray['errcode']=0;
        $returnArray = http_request_curl($mass_api_url,$jsonStr);

        if ($returnArray['errcode'] == 0){
            setSend($msgInfo['id']);
            die(json_encode('suc'));
        }
        die(json_encode($returnArray['errmsg']));
    }

    //上传图片素材取得meida_id
    function upImage($pic,$token) {
        $upFileUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=image";
        $imgPath = ROOT_PATH.'data/image_c/'.$pic;
        $data = array('media'=>'@'.$imgPath);
        $info = http_request_curl($upFileUrl,$data);
        if($info['media_id']){
            return $info['media_id'];
        }else{
            die(json_encode('图片素材上传失败'));
        }
    }
    
    //设置某个文字或图文素材已发送
    function setSend($id){
        $infoModel=new Model_InfoCommon();
        if($id) $infoModel->row_update(array('is_send'=>1),"id='{$id}'");
    }

    //curl返回数组
    function http_request_curl($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,ture);
    }
    